﻿using System.Reflection;
using System;

namespace Chen.IdentityServer4.Models
{
    /// <summary>
    /// 获取枚举类型的备注
    /// </summary>
    public static class EnumHelper
    {
        /// <summary>
        /// 获取枚举文字
        /// </summary>
        /// <param name="enumValue">枚举值</param>
        public static string GetDescriptionText(this Enum enumValue)
        {
            //获取枚举项
            Type t = enumValue.GetType();
            //获取枚举项的字段
            FieldInfo[] fis = t.GetFields();
            foreach (FieldInfo fi in fis)
            {
                //如果当前字段名称不是当前枚举项
                if (fi.Name != enumValue.ToString())
                    continue;

                //如果当前字段的包含自定义特性
                if (fi.IsDefined(typeof(EnumNameAttribute), true))
                    return (fi.GetCustomAttributes(typeof(EnumNameAttribute), true)[0] as EnumNameAttribute).Text;
            }
            return enumValue.ToString();
        }
    }

    /// <summary>
    /// 枚举类型备注名称特性
    /// </summary>
    [AttributeUsage(AttributeTargets.Field)]
    public class EnumNameAttribute : Attribute
    {
        public String Text
        {
            get;
            set;
        }

        public EnumNameAttribute(String text)
        {
            this.Text = text;
        }
    }
}
